/*
 * v1.1 by tonydon site:txdnet.cn
 * netbeansIDE 7.1
 */
package cn.txdnet.txcms.auth;

import cn.txdnet.txcms.domain.Manager;
import cn.txdnet.txweb.utils.SessionUtil;
import cn.txdnet.txweb.utils.WebUtil;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import txdnet.util.Logger;

/**
 *
 * @author txdnet
 */
public class AdminRoleAccessFilter implements Filter {

    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private String method_suffix = "()";
    private FilterConfig filterConfig = null;

    public AdminRoleAccessFilter() {
    }

    private boolean doBeforeProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Object obj = SessionUtil.getManager(req);
        if (obj == null) {
            return false;
        }
        String servletPath = req.getServletPath();
        String pathInfo = req.getPathInfo();
        String url = WebUtil.getRequestUrl(servletPath, pathInfo);
        String methodstr = WebUtil.getUrlMethod(url);
        String urlaction = WebUtil.getUrlAction(url);

        if (methodstr.length() == 0) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "NOT_DEFINED_METHOD");
            return false;
        }
        if (urlaction.equals(servletPath)) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "NOT_FOUND_ACTION_PATH");
            return false;
        }
        AdminRoleAccessBean rolebean = AdminRoleAccessConfig.getRoleAccessBean(urlaction);
        // 访问的Action Path 是否有角色控制
        if (rolebean != null) {
            String methods = rolebean.getMethods();
            String role = rolebean.getRole();
            String rolelevel = ((Manager) obj).getRolelevel();
            if (methods.length() == 1 || methods.indexOf(methodstr.concat(method_suffix)) >= 0) {
                // 匹配到了指定的方法访问 如果没有赋予该角色，则拒绝访问
                if (rolelevel.indexOf(role) < 0) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {


        if (!doBeforeProcessing(request, response)) {
            HttpServletResponse res = (HttpServletResponse) response;
            res.setContentType("text/plain");
            res.getWriter().println("Admin Role Access Deny.");
            return;
        }

        Throwable problem = null;
        try {
            chain.doFilter(request, response);
        } catch (Throwable t) {
            // If an exception is thrown somewhere down the filter chain,
            // we still want to execute our after processing, and then
            // rethrow the problem after that.
            problem = t;
            Logger.error(AdminSessionFilter.class, t.toString());
        }

        // If there was a problem, we want to rethrow it if it is
        // a known type, otherwise log it.
        if (problem != null) {
            if (problem instanceof ServletException) {
                throw (ServletException) problem;
            }
            if (problem instanceof IOException) {
                throw (IOException) problem;
            }
            sendProcessingError(problem, response);
        }
    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter
     */
    @Override
    public void destroy() {
    }

    /**
     * Init method for this filter
     */
    @Override
    public void init(FilterConfig filterConfig) {
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("AdminSessionFilter()");
        }
        StringBuilder sb = new StringBuilder("AdminSessionFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }

    private void sendProcessingError(Throwable t, ServletResponse response) {
        String stackTrace = getStackTrace(t);

        if (stackTrace != null && !stackTrace.isEmpty()) {
            try {
                response.setContentType("text/html");
                PrintStream ps = new PrintStream(response.getOutputStream());
                PrintWriter pw = new PrintWriter(ps);
                pw.print(stackTrace);
                pw.close();
                ps.close();
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        } else {
            try {
                PrintStream ps = new PrintStream(response.getOutputStream());
                t.printStackTrace(ps);
                ps.close();
                response.getOutputStream().close();

            } catch (Exception ex) {
            }
        }
    }

    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            sw.close();
            stackTrace = sw.getBuffer().toString();
            Logger.error(AdminSessionFilter.class, stackTrace);
        } catch (Exception ex) {
        }
        return stackTrace;
    }

}
